package com.zl.autocode.service.base;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zl.autocode.common.constant.AutocodeConfigC;
import com.zl.common.enums.resp.GlobalRespEnum;
import com.zl.common.exception.BizException;
import com.zl.service.base.BaseManager;

import cn.hutool.core.util.StrUtil;

/**
 * 某些普遍方法再次封装，减少引入快速使用
 * @author zhouliang
 *
 */
public class AutocodeBaseManager extends BaseManager{

    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
    
    public static Map<String,String> AUTOCODE_MAP = new HashMap<>();
    
    /** 组装文件路径*/
    public static String filePath(String mainPath, String mainPath2, String[] otherPaths){
        String separatorStr = File.separator;
        
        //不能丢失目录，否则会会删除目录下的文件
        if(StringUtils.isBlank(mainPath) || StringUtils.isBlank(mainPath2)){
            throw new BizException(GlobalRespEnum.MISSING_FILE.getCode(), GlobalRespEnum.MISSING_FILE.getMsg());
        }
        
        String extpath = "";
        if(otherPaths != null){
            for(String pathx : otherPaths){
                if(pathx.contains("---")){
                    String[] tp = pathx.split("---");
                    if(tp[0].length()<Integer.valueOf(tp[1])){
                        pathx = StrUtil.padPre(tp[0], Integer.valueOf(tp[1]), "0");
                    }else{
                        pathx = tp[0];
                    }
                }
                extpath = extpath + pathx + separatorStr;
            }
        }
        
        mainPath = mainPath.replaceAll("(\\\\)+", "/");
        
        if(mainPath.startsWith("/")){
            mainPath = mainPath.replaceFirst("(/)+", "");
        }
        if(!mainPath.endsWith("/")){
            mainPath = mainPath + "/";
        }
        if(mainPath2.startsWith("/")){
            mainPath2 = mainPath2.replaceFirst("(/)+", "");
        }
        if(!mainPath2.endsWith("/")){
            mainPath2 = mainPath2 + "/";
        }
        mainPath = mainPath + mainPath2;
        
        mainPath = mainPath + extpath;
        
        mainPath = mainPath.replaceAll("(\\\\)+", "/");
        mainPath = mainPath.replaceAll("(/)+", "/");
        return mainPath;
    }
    
    /**
     * 把相对目录转换一下
     * @param path
     * @return
     */
    public String handlerRootPath(String path){
        if(StringUtils.isBlank(path)) {
            return null;
        }
        path =  AUTOCODE_MAP.get(AutocodeConfigC.AUTOCODE_FACT_ROOT) + "/" + path;
        path = path.replaceAll("(/)+", "/");
        return path;
    }
 }